type DataType = { code: string, children?: DataType[] }


const pcas = require('./pcas-code')

const TOPLEVEL = {children: pcas, code: 'cn'}

export function pca2ToStreets(pca: string): { code: string, name: string }[] {
  const pCode = pca.slice(0, 2)
  const pcCode = pca.slice(0, 4)
  const pcaCode = pca.slice(0, 6)

  const provinceData = pcas.find(({code}) => code === pCode)
  const cityData = provinceData.children.find(({code}) => code === pcCode)
  const areaData = cityData.children.find(({code}) => code === pcaCode)

  return areaData.children
}

const segLength = [2, 4, 6, 9]


const generateFinderForLevel = (level: 1 | 2 | 3 | 4) => function (pca: string): DataType {

  if (pca.length !== segLength[level - 1]) {
    return null
  }

  return segLength.slice(0, level).reduce((currentLevel: DataType, len) => {

    if (!currentLevel) {
      return currentLevel
    }
    const code = pca.slice(0, len)
    return currentLevel.children.find(c => c.code === code)

  }, TOPLEVEL)
}

export function pcasByCode(pcasCode: string) {

  let currentLevel = TOPLEVEL

  return segLength.map((l) => {
    const segCode = pcasCode.slice(0, l)

    const children = currentLevel.children.find(({code}) => code === segCode)

    const {name, code} = children
    currentLevel = children

    return {name, code}
  })

}


export const findAreaByPcaCode = generateFinderForLevel(3)
export const findStreetByPcasCode = generateFinderForLevel(4)
export const isValidatePcaCode = (code: string) => !!findAreaByPcaCode(code)
export const isValidatePcasCode = (code: string) => !!findStreetByPcasCode(code)
